package com.github.tetrisgame.utils;

import static android.app.Activity.RESULT_OK;

import android.content.Intent;
import android.net.Uri;
import android.provider.MediaStore;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;

import java.io.FileNotFoundException;
import java.lang.ref.WeakReference;

public class SkipToPhotoAlbum {
    public static SkipToPhotoAlbum sharedInstance = new SkipToPhotoAlbum();
    private OnGetPhotoListener onGetPhotoListener;
    private WeakReference<AppCompatActivity> weakActivity;
    private ActivityResultLauncher<Intent> launcher;

    private SkipToPhotoAlbum() {

    }

    public void init(AppCompatActivity activity) {
        weakActivity = new WeakReference<>(activity);
        launcher = activity.registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result.getResultCode() == RESULT_OK) {
                Intent dataIntent = result.getData();
                if (dataIntent != null) {
                    Uri selectedPhotoUri = dataIntent.getData();
                    if (onGetPhotoListener != null) {
                        try {
                            onGetPhotoListener.getPhoto(selectedPhotoUri);
                        } catch (FileNotFoundException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        });
    }

    public void openPhotoAlbum(OnGetPhotoListener listener) {
        this.onGetPhotoListener = listener;
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        launcher.launch(intent);
    }

    public interface OnGetPhotoListener {
        void getPhoto(Uri selectedPhotoUri) throws FileNotFoundException;
    }
}
